import {
  // getUserInfo,
  getMessage,
  getContentByMsgId,
  hasRead,
  removeReaded,
  restoreTrash,
  getUnreadCount
} from '@/api/user'
import { login, logout } from '@/api/data2'
import {
  setCookiesInfo,
  getCookiesInfo,
  clearCookiesInfo,
  setTagNavListInLocalstorage,
  setFrontTagNavListInLocalstorage
} from '@/libs/util'

const cookiesInfos = getCookiesInfo()

export default {
  state: {
    userName: cookiesInfos.username || '',
    userId: '',
    avatarImgPath: '',
    token: cookiesInfos.token || '',
    access: '',
    hasGetInfo: false,
    unreadCount: 0,
    messageUnreadList: [],
    messageReadedList: [],
    messageTrashList: [],
    messageContentStore: {},
    operatorId: cookiesInfos.operatorId || 0,
    stationId: cookiesInfos.stationId || 0,
    menuList: cookiesInfos.menuList || [],
    rolename: cookiesInfos.rolename || ''
  },
  mutations: {
    setOperatorId (state, id) {
      state.operatorId = id
    },
    setStationId (state, id) {
      state.stationId = id
    },
    setRolename (state, name) {
      state.rolename = name
    },
    setAvatar (state, avatarPath) {
      state.avatarImgPath = avatarPath
    },
    setUserId (state, id) {
      state.userId = id
    },
    setUserName (state, name) {
      state.userName = name
    },
    setAccess (state, access) {
      state.access = access
    },
    setToken (state, token) {
      state.token = token
    },
    setMenuList (state, list) {
      state.menuList = list
    },
    setHasGetInfo (state, status) {
      state.hasGetInfo = status
    },
    setMessageCount (state, count) {
      state.unreadCount = count
    },
    setMessageUnreadList (state, list) {
      state.messageUnreadList = list
    },
    setMessageReadedList (state, list) {
      state.messageReadedList = list
    },
    setMessageTrashList (state, list) {
      state.messageTrashList = list
    },
    updateMessageContentStore (state, { msg_id, content }) {
      state.messageContentStore[msg_id] = content
    },
    moveMsg (state, { from, to, msg_id }) {
      const index = state[from].findIndex(_ => _.msg_id === msg_id)
      const msgItem = state[from].splice(index, 1)[0]
      msgItem.loading = false
      state[to].unshift(msgItem)
    },
    clearState (state) {
      // console.log('[user] clear state ...')
      state.token = ''
      state.userName = ''
      state.operatorId = ''
      state.stationId = ''
      state.rolename = ''
      state.menulist = []
    }
  },
  getters: {
    messageUnreadCount: state => state.messageUnreadList.length,
    messageReadedCount: state => state.messageReadedList.length,
    messageTrashCount: state => state.messageTrashList.length,
    isAdmin (state) {
      return state.stationId == 0 && state.operatorId == 0
    },
    isAgent (state) {
      return state.operatorId > 0 && state.stationId == 0
    },
    isStation (state) {
      return state.operatorId > 0 && state.stationId > 0
    }
  },
  actions: {
    // 登录
    handleLogin ({ commit }, { userName, password }) {
      return new Promise((resolve, reject) => {
        login({
          userName,
          password
        })
          .then(res => {
            if (res.code == 200) {
              const {
                token,
                username,
                operatorid,
                stationid,
                menulist,
                rolename
              } = res.data
              commit('setToken', token)
              commit('setUserName', username)
              commit('setOperatorId', operatorid)
              commit('setStationId', stationid)
              commit('setMenuList', menulist || [])
              commit('setRolename', rolename)
              setCookiesInfo({
                token,
                username,
                operatorId: operatorid,
                stationId: stationid,
                menuList: menulist || [],
                rolename
              })
            }
            resolve(res)
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        if (state.token) {
          logout({
            userName: state.userName,
            token: state.token
          })
            .then(res => {
              if (res.code == 200) {
                commit('clearState')
                clearCookiesInfo()
                setTagNavListInLocalstorage([])
                setFrontTagNavListInLocalstorage([])
              }
              resolve(res)
            })
            .catch(err => {
              reject(err)
            })
        } else {
          commit('clearState')
          clearCookiesInfo()
          setTagNavListInLocalstorage([])
          setFrontTagNavListInLocalstorage([])
          resolve({ code: 200 })
        }
      })
    },
    // 获取用户相关信息
    getUserInfo ({ state, commit }) {
      // return new Promise((resolve, reject) => {
      //   try {
      //     getUserInfo(state.token).then(res => {
      //       const data = res.data
      //       commit('setAvatar', data.avatar)
      //       commit('setUserName', data.name)
      //       commit('setUserId', data.user_id)
      //       commit('setAccess', data.access)
      //       commit('setHasGetInfo', true)
      //       resolve(data)
      //     }).catch(err => {
      //       reject(err)
      //     })
      //   } catch (error) {
      //     reject(error)
      //   }
      // })
      const data = {
        name: state.userName,
        token: state.token,
        operatorId: state.operatorId,
        stationId: state.stationId,
        menuList: state.menuList,
        rolename: state.rolename,
        user_id: '1',
        access: ['super_admin', 'admin'],
        // token: 'super_admin',
        avatar:
          'https://file.iviewui.com/dist/a0e88e83800f138b94d2414621bd9704.png'
      }
      return new Promise((resolve) => {
        commit('setAvatar', data.avatar)
        // commit('setUserName', data.name)
        commit('setUserId', data.user_id)
        commit('setAccess', data.access)
        commit('setHasGetInfo', true)
        resolve(data)
      })
    },
    // 此方法用来获取未读消息条数，接口只返回数值，不返回消息列表
    getUnreadMessageCount ({ commit }) {
      getUnreadCount().then(res => {
        const { data } = res
        commit('setMessageCount', data)
      })
    },
    // 获取消息列表，其中包含未读、已读、回收站三个列表
    getMessageList ({ commit }) {
      return new Promise((resolve, reject) => {
        getMessage()
          .then(res => {
            const { unread, readed, trash } = res.data
            commit(
              'setMessageUnreadList',
              unread.sort(
                (a, b) => new Date(b.create_time) - new Date(a.create_time)
              )
            )
            commit(
              'setMessageReadedList',
              readed
                .map(_ => {
                  _.loading = false
                  return _
                })
                .sort(
                  (a, b) => new Date(b.create_time) - new Date(a.create_time)
                )
            )
            commit(
              'setMessageTrashList',
              trash
                .map(_ => {
                  _.loading = false
                  return _
                })
                .sort(
                  (a, b) => new Date(b.create_time) - new Date(a.create_time)
                )
            )
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 根据当前点击的消息的id获取内容
    getContentByMsgId ({ state, commit }, { msg_id }) {
      return new Promise((resolve) => {
        const contentItem = state.messageContentStore[msg_id]
        if (contentItem) {
          resolve(contentItem)
        } else {
          getContentByMsgId(msg_id).then(res => {
            const content = res.data
            commit('updateMessageContentStore', { msg_id, content })
            resolve(content)
          })
        }
      })
    },
    // 把一个未读消息标记为已读
    hasRead ({ state, commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        hasRead(msg_id)
          .then(() => {
            commit('moveMsg', {
              from: 'messageUnreadList',
              to: 'messageReadedList',
              msg_id
            })
            commit('setMessageCount', state.unreadCount - 1)
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 删除一个已读消息到回收站
    removeReaded ({ commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        removeReaded(msg_id)
          .then(() => {
            commit('moveMsg', {
              from: 'messageReadedList',
              to: 'messageTrashList',
              msg_id
            })
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 还原一个已删除消息到已读消息
    restoreTrash ({ commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        restoreTrash(msg_id)
          .then(() => {
            commit('moveMsg', {
              from: 'messageTrashList',
              to: 'messageReadedList',
              msg_id
            })
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    }
  }
}
